import socket

import requests
import websocket
from websocket import ABNF
import json
import _thread
import time

url = "ws://system.stead:2346/"  # 接口地址
global reconnect_count
reconnect_count = 1


def on_message(ws, message):
    print(message)


def on_error(ws, error):
    global reconnect_count
    print(error)
    if type(error) == ConnectionRefusedError or type(error) == websocket._exceptions.WebSocketConnectionClosedException:
        print("正在尝试第%d次重连" % reconnect_count)
        reconnect_count += 1
        time.sleep(1)
        if reconnect_count < 100:
            connection_tmp(ws)
    else:
        print("其他error!")


def connection_tmp(ws):
    websocket.enableTrace(True)
    print(url)
    ws = websocket.WebSocketApp(url,
                                on_message=on_message,
                                #   on_data=on_data_test,
                                on_error=on_error,
                                on_close=on_close)

    ws.on_open = on_open
    try:
        ws.run_forever()
    except KeyboardInterrupt:
        ws.close()
    except:
        ws.close()


def on_close(ws):
    print("连接关闭！")


def on_open(ws):
    def run(*args):
        ws.send('ping')
        while True:
            ws.send(json.dumps({'is_pc': True}))
            time.sleep(3.5)

    _thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(url,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close)
    ws.on_open = on_open
    ws.run_forever()
